<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-09 11:07:23
 * @LastEditTime: 2024-04-16 13:04:32
 * @LastEditors: yl
 * @Description: 个人溯源信息
-->
<template>
  <BaseMainSlot
    v-loading="downLoading"
    element-loading-text="拼命下载中"
    element-loading-spinner="el-icon-loading"
    :show-tab="false"
    :show-search-box="false"
  >
    <template v-slot:btn-box>
      <ActionBar
        v-show="!showTraceInfo"
        :page-no="604"
        :add-active="addActive"
        :import-active="importActive"
        :export-active="true"
        :del-active="delActive"
        :edit-active="editActive"
        :has-edit="false"
        :has-save="false"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox v-show="!showTraceInfo" @search="search">
        <div class="common-search-item">
          <div class="label"></div>
          <div class="input"></div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <ZnFilterTable
        v-if="tableUpStauts === 1&&!showTraceInfo"
        :loadings="loading"
        :list-data="tableData"
        :prop-list="tableDataList"
        scope-no="traceConfigNo"
        @handleSelectionChange="handleSelectionChange"
        @tableUpdate="tableUpdate"
      >
        <template v-slot:url="{ row }">
          <el-image
            v-if="row.urlList"
            style="max-width: 100px; max-height: 50px"
            :src="row.urlList&&row.urlList[0]"
            :preview-src-list="row.urlList"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
        <template v-slot:operation="{ row }">
          <template>
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleTraceInfor(row)"
            >
              查看溯源信息
            </el-button>
            <el-button
              v-if="judgePermission(604, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-else-if="!judgePermission(604, 'edit')"
              disabled
              class="text-btn-cursor"
              type="text"
              size="small"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(604, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.traceConfigNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button
              v-else-if="!judgePermission(604, 'delete')"
              disabled
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
      </znfiltertable>
      <Pagination
        v-show="!showTraceInfo"
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
      <TraceInformation v-show="showTraceInfo" ref="traceInfo" @back="TraceInforClose" />
    </template>
    <template v-slot:dialog>
      <el-dialog id="tableColumnDialog" title="配置列" :visible.sync="dialogTableColumnVisible">
        <tableColumn v-if="dialogTableColumnVisible" ref="tableColumn" :table-column="allTableColumn" @cancelColumn="cancelColumn" />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="saveColumn">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        :title="titleText + livestock(textRouteName)"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <!-- 基础信息 -->
          <!-- <span>{{ '' }}</span> -->
          <el-divider content-position="left">产品信息</el-divider>

          <template
            v-for="item,index in JSON.parse(livestock(JSON.stringify(formDataList)))"
          >
            <el-form-item
              v-if="item.show"
              :key="index"
              :label="item.name + ':'"
              :prop="item.porp"
              :class="item.width || 'w100p'"
              :rules="item.number? [
                { required: item.required, message: item.name + '不能为空', trigger: ['blur' ,'change']},
                { validator: item.number ? validateNumber : false, trigger: 'blur'},]:[
                  { required: item.required, message: item.name + '不能为空', trigger: ['blur' ,'change']}
                ]"
            >
              <el-input
                v-if="item.type === 'input'"
                v-model="formData[ `${item.porp}`]"
                :placeholder="'请输入' + item.name"
                clearable
                :disabled="item.disable||false"
              >
                <span v-if="item.sortName" :slot="item.sortName">
                  {{ item.unitName }}
                </span>
              </el-input>
              <el-date-picker
                v-if="item.type === 'date'"
                v-model="formData[ `${item.porp}`]"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="item.porp === 'birthday'&&endDatePicker"
                :placeholder="'请输入' + item.name"
                clearable
              />
              <el-date-picker
                v-if="item.type === 'dateRange'"
                v-model="formData[ `${item.porp}`]"
                type="daterange"
                :picker-options="startDatePicker"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                clearable
              />
              <el-select
                v-if="item.type === 'Select'"
                v-model="formData[ `${item.porp}`]"
                filterable
                :placeholder="'请选择' + item.name"
                clearable
                @change="SelectLinkage($event, item.linkage, index,'manufacturerNo',item)"
              >
                <el-option
                  v-for="items,indexs in item.typeObj&&item.typeObj.list"
                  :key="indexs"
                  :label="items[item.typeObj&&item.typeObj.listName&&item.typeObj.listName[0]] || items.name"
                  :value="livestockInvert(items[item.typeObj&&item.typeObj.listName&&item.typeObj.listName[1]] || items.value)"
                />
              </el-select>
              <UploadPics
                v-if="item.type === 'img'"
                ref="UploadPics"
                v-model="productUploadPictureList"
                :limit="1"
                :disabled="item.disabled"
                accept=".jpg, .jpeg, .png"
                @input="handlerAddFileList($event, item.porpLink)"
                @delectFileId="handlerDeleteId($event, item.porpLink)"
              />
            </el-form-item>
          </template>
          <el-divider content-position="left">主体信息</el-divider>
          <div
            class="w100p"
            style="display: flex;flex-wrap: wrap; position: relative;"
          >
            <template
              v-for="item,index in JSON.parse(livestock(JSON.stringify(formDataOBj['Manufacturer'])))"
            >
              <el-form-item
                v-if="item.show"
                :key="index + item.name"
                :label="item.name + ':'"
                :prop="item.porpLink ? `${item.porp}.${item.porpLink}` : item.porp"
                :class="item.width || 'w100p'"
                :rules="item.number? [
                  { required: item.required, message: item.name + '不能为空', trigger: ['blur' ,'change']},
                  { validator: item.number ? validateNumber : false, trigger: 'blur'},]:[
                    { required: item.required, message: item.name + '不能为空', trigger: ['blur' ,'change']}
                  ]"
              >
                <el-input
                  v-if="item.type === 'input'"
                  v-model="formData[`${item.porp}`][`${item.porpLink}`]"
                  :placeholder="'请输入' + item.name"
                  clearable
                  :disabled="item.disable||false"
                >
                  <span v-if="item.sortName" :slot="item.sortName">
                    {{ item.unitName }}
                  </span>
                </el-input>
                <el-input
                  v-if="item.type === 'textarea'"
                  v-model="formData[`${item.porp}`][`${item.porpLink}`]"
                  type="textarea"
                  autosize
                  class="w100p"
                  :placeholder="'请输入' + item.name"
                  clearable
                  :disabled="item.disable||false"
                />
                <el-select
                  v-if="item.type === 'Select'"
                  v-model="formData[`${item.porp}`][`${item.porpLink}`]"
                  filterable
                  :placeholder="'请选择' + item.name"
                  clearable
                  :disabled="item.disable||false"
                  @change="SelectLinkage($event, item.linkage, index,'proprietorNo',item)"
                >
                  <el-option
                    v-for="items,indexs in item.typeObj&&item.typeObj.list"
                    :key="indexs"
                    :label="items[item.typeObj&&item.typeObj.listName&&item.typeObj.listName[0]] || items.name"
                    :value="livestockInvert(items[item.typeObj&&item.typeObj.listName&&item.typeObj.listName[1]] || items.value)"
                  />
                </el-select>

                <UploadPics
                  v-if="item.type === 'img'"
                  ref="UploadPics"
                  v-model="proprietorloadPictureList"
                  :limit="4"
                  accept=".jpg, .jpeg, .png"
                  :disabled="item.disable||false"
                />
              </el-form-item>

            </template>
          </div>
          <el-divider content-position="left">检测报告</el-divider>
          <div
            v-for="item,index in formData['testReportInfoList']"
            :key="index + 'testReportInfoList'"
            class="w100p"
            style="display: flex;flex-wrap: wrap; position: relative;"
          >
            <template v-for="inspectionItem, inspectionIndex in JSON.parse(livestock(JSON.stringify(formDataOBj['inspection'])))">
              <el-form-item
                v-if="inspectionItem.show"
                :key="inspectionIndex + inspectionItem.name"
                :label="inspectionItem.name + ':'"
                :prop="'testReportInfoList.' + index + '.' + inspectionItem.porp"
                :class="inspectionItem.width || 'w100p'"
                :rules="inspectionItem.number? [
                  { required: inspectionItem.required, message: inspectionItem.name + '不能为空', trigger: ['blur' ,'change']},
                  { validator: inspectionItem.number ? validateNumber : false, trigger: 'blur'},]:[
                    { required: inspectionItem.required, message: inspectionItem.name + '不能为空', trigger: ['blur' ,'change']}
                  ]"
              >
                <el-input
                  v-if="inspectionItem.type === 'input'"
                  v-model="item[ `${inspectionItem.porp}`]"
                  :placeholder="'请输入' + inspectionItem.name"
                  clearable
                >
                  <span v-if="inspectionItem.sortName" :slot="inspectionItem.sortName">
                    {{ inspectionItem.unitName }}
                  </span>
                </el-input>
                <el-date-picker
                  v-if="inspectionItem.type === 'date'"
                  v-model="item[ `${inspectionItem.porp}`]"
                  type="date"
                  value-format="yyyy-MM-dd"
                  :placeholder="'请输入' + inspectionItem.name"
                  clearable
                />
                <UploadPics
                  v-if="inspectionItem.type === 'img'"
                  ref="UploadPics"
                  v-model="reportUploadPictureList[index]"
                  :limit="4"
                  accept=".jpg, .jpeg, .png"
                  @input="handlerAddFileList($event, inspectionItem.porpLink,index)"
                  @delectFileId="handlerDeleteId($event, inspectionItem.porpLink,index)"
                />
              </el-form-item>
            </template>
            <div class="w100p addE">
              <div
                v-if="nowChanceStau ==='edit' && formData.testReportInfoList.length > 1&& item.traceConfigNo"
                class="line-clicks"
                @click="delCountList(item, 'testReport', index)"
              >删除</div>
              <div
                v-if="(formData.testReportInfoList.length > 1 && nowChanceStau === 'add') || (formData.testReportInfoList.length > 0 && nowChanceStau ==='edit' && !item.traceConfigNo)"
                class="line-click"
                @click="() => {formData.testReportInfoList.splice(index, 1),reportUploadPictureList.splice(index, 1)}"
              >
                <i class="el-icon-minus"></i>
              </div>
              <div
                v-if="nowChanceStau === 'add' && index === formData.testReportInfoList.length - 1 || nowChanceStau ==='edit' && index === formData.testReportInfoList.length - 1 "
                class="line-click"
                @click="() => {formData.testReportInfoList.push({}),reportUploadPictureList.push([])}"
              >
                <i class="el-icon-plus"></i>
              </div>
            </div>
          </div>
          <el-divider content-position="left">环境数据</el-divider>
          <div
            class="w100p"
            style="display: flex;flex-wrap: wrap; position: relative;"
          >

            <template
              v-for="item,index in formData['environmentalDataList']"
            >
              <!-- <template
                v-for="EnvironmentalItem,EnvironmentalIndex in JSON.parse(livestock(JSON.stringify(formDataOBj['Environmental'])))"
              > -->
              <el-form-item
                v-if="formDataOBj['Environmental'][index]&&formDataOBj['Environmental'][index].show"
                :key="index + formDataOBj['Environmental'][index].name"
                :label="formDataOBj['Environmental'][index].name + ':'"
                :prop="`environmentalDataList.${index}.value`"
                :class="formDataOBj['Environmental'][index].width || 'w100p'"
                :rules="formDataOBj['Environmental'][index].number? [
                  { required: formDataOBj['Environmental'][index].required, message: formDataOBj['Environmental'][index].name + '不能为空', trigger: ['blur' ,'change']},
                  { validator: formDataOBj['Environmental'][index].number ? validateNumber : false, trigger: 'blur'},]:[
                    { required: formDataOBj['Environmental'][index].required, message: formDataOBj['Environmental'][index].name + '不能为空', trigger: ['blur' ,'change']}
                  ]"
              >
                <el-input
                  v-if="formDataOBj['Environmental'][index].type === 'input'"
                  v-model="item[`${formDataOBj['Environmental'][index].porpLink}`]"
                  :placeholder="'请输入' + formDataOBj['Environmental'][index].name"
                  clearable
                >
                  <span v-if="formDataOBj['Environmental'][index].sortName" :slot="formDataOBj['Environmental'][index].sortName">
                    {{ formDataOBj['Environmental'][index].unitName }} {{ sortRow(formDataOBj['Environmental'][index], index) }}
                  </span>
                </el-input>
              </el-form-item>
              <!-- </template> -->

            </template>
            <template v-for="environmentalData,indexs in formData['AddEnvironmentalDataList']">
              <el-form-item
                :key="indexs"
                class="w50p environmental"
                style="position: relative;"
              >
                <el-form-item
                  label="数据项"
                  :rules="[ { required: true, message: '数据类型不能为空', trigger: ['blur','change'] }]"
                  :prop="`AddEnvironmentalDataList.${indexs}.dataItemName`"
                >
                  <el-input
                    v-model="environmentalData.dataItemName"
                    placeholder="请输入数据类型"
                    clearable
                  />
                </el-form-item>
                <el-form-item
                  :rules="[ { required: true, message: '数据类型不能为空', trigger: ['blur','change'] } ]"
                  :prop="`AddEnvironmentalDataList.${indexs}.value`"
                >
                  <el-input
                    v-model="environmentalData.value"
                    placeholder="请输入数据值"
                    clearable
                  />
                </el-form-item>
                <el-form-item>
                  <el-input
                    v-model="environmentalData.unitSymbol"
                    placeholder="请输入单位"
                    clearable
                  />
                </el-form-item>
                <div
                  class="line-click"
                  @click="() => {environmentalDataList.splice(indexs, 1)}"
                >
                  <i class="el-icon-minus"></i>
                </div>
              </el-form-item>
            </template>
            <div class="w100p addE">

              <div
                class="line-click"
                style="right: -26px;
                        margin-bottom: 21px;"
                @click="addEnvironmentalData"
              >
                <i class="el-icon-plus"></i>
              </div>
            </div>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>

    </template>

  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { tableDataList, formDataList, formDataOBj } from "./farmdataList";
import { dateToFormattwo } from '@/utils/validate';
import UploadPics from "@/components/UploadPics/upload-img-list.vue";
import traceConfigApi from "@/api/trace-source-web/traceConfig.js";
// 养殖品种
import breedVarietiesApi from "@/api/trace-source-web/base-infor-manage/breed-varieties-management.js";
// 生产单位
import manufacturerInfoApi from "@/api/trace-source-web/base-infor-manage/manufacturer-management.js";
// 主体信息
import proprietorrApi from "@/api/trace-source-web/base-infor-manage/proprietorr-management.js";
// 产品信息
import productInfoApi from "@/api/trace-source-web/base-infor-manage/product-infor-management.js";
// 溯源信息展示修改页面
import TraceInformation from "@/views/trace-source-web/components/traceability-information/index.vue";

// import
export default {
  name: "EnterTraceabilityInformation",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot,
    SearchBox,
    UploadPics,
    TraceInformation
  },
  mixins: [mymixin],
  data() {
    let validateNumber = (rule, value, callback) => {
      let patt = /^[+]?(\d+)$|^[+]?(\d+\.\d+)$/;
      if (value) {
        if (value !== "" && !patt.test(value)) {
          callback(new Error("值为大于0数"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      // 主体图片
      proprietorloadPictureList: [],
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      // 产品图片
      productUploadPictureList: [],
      // 报告图片
      reportUploadPictureList: [],
      // 溯源信息
      traceInfo: {},
      showTraceInfo: false,
      formStuats: true,
      validateNumber: validateNumber,
      groupFlag: true,
      // 员工姓名
      traceConfigNo: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      selectedList: [],
      initialParameters: {},
      files: {},
      upLoading: false,
      downLoading: false,
      formData: {
        manufacturerInfo: {},
        environmentalDataList: [{}, {}, {}, {}, {}],
        testReportInfoList: [{}],
        AddEnvironmentalDataList: []
      },
      environmentalDataList: [],
      tableDataList: tableDataList,
      formDataList: formDataList,
      formDataOBj: formDataOBj,
      fatherList: [],
      motherList: [],
      topitemtypestu: true,
      searchObj: {},
      // 脱敏 start
      List: {}
      // 脱敏 end
    };
  },
  watch: {
  },
  created() {
  },
  mounted() {
    this.getList();
    this.search();
  },
  methods: { // 限制前面日期不能低于后面日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.birthday) {
            //  如果结束时间不为空，则小于结束时间
            return (
              time.getTime() <=
                new Date(self.formData?.birthday).getTime() - 8.64e7 ||
              time.getTime() > new Date().getTime()
            );
          } else {
            //  如果结束时间不为空，则小于结束时间
            return new Date().getTime() < time.getTime();
          }
        }
      };
    },
    processDate() {
      // let self = this
      return {
        disabledDate(time) {
          return new Date().getTime() < time.getTime();
        }
      };
    },
    addEnvironmentalData() {
      let environmentalData = {
        value: "",
        unitSymbol: '',
        dataItemName: ""
      }
      this.environmentalDataList.push(environmentalData)
      this.$set(this.formData, 'AddEnvironmentalDataList', this.environmentalDataList)
      console.log("addEnvironmentalData", this.formData, this.environmentalDataList);
    },
    // 添加-品种图片
    handlerAddFileList(data, type, inspectionIndex = 0) {
      if (type === "product") {
        this.productUploadPictureList = data.list;
        this.formData.urlList = data.list;
      } else if (type === "proprietor") {
        this.proprietorloadPictureList = data.list;
        this.formData.testReportInfoList[inspectionIndex].urlList = data.list
      } else {
        this.reportUploadPictureList[inspectionIndex] = data.list;
        this.formData.testReportInfoList[inspectionIndex].urlList = data.list.map(item => { return item.url })
      }
    },

    // 删除-轮播图/视频
    handlerDeleteId(file, type, inspectionIndex = 0) {
      // this.$confirm()
      this.$confirm(
        `确认删除该${
          type === "png" ? "图片" : type === "video" ? "视频" : "文件"
        }`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          customClass: "myClass"
        }
      )
        .then(() => {
          // console.log(file)
          let fileId = file.url;
          if (type === "product") {
            this.productUploadPictureList.splice(
              this.productUploadPictureList.findIndex((i) => i.url == fileId),
              1
            );
            this.formData.url = ''
          } else {
            let newList = []
            let index = 0
            console.log("handlerDeleteId1", inspectionIndex, this.reportUploadPictureList);
            for (let i = 0; i < this.reportUploadPictureList[inspectionIndex].length; i++) {
              let item = this.reportUploadPictureList[inspectionIndex][i]
              if (item.url !== fileId) {
                newList.push(item)
              } else {
                index = i
              }
            }
            this.$set(this.reportUploadPictureList, inspectionIndex, newList)

            this.formData.testReportInfoList[inspectionIndex].urlList.splice(index, 1)
            console.log("handlerDeleteId2", this.formData.testReportInfoList[inspectionIndex]);
          }
        })
        .catch((e) => {
          console.log(e);
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 查看溯源信息
    handleTraceInfor(row) {
      this.showTraceInfo = true;
      this.$refs['traceInfo'].queryTraceInfo(row, 604);
    },

    TraceInforClose(refresh) {
      if (refresh) {
        this.search();
      }
      this.showTraceInfo = false;
    },

    async getList() {
      breedVarietiesApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: "formDataList",
          porp: "breedVarietyNo",
          list: res.data,
          listName: ["breedVarietyName", "breedVarietyNo"]
        });
      })
      productInfoApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: "formDataList",
          porp: "productNo",
          list: res.data,
          listName: ["productName", "productNo"]
        });
        this.listfor({
          formDataList: "tableDataList",
          porp: "productName",
          list: res.data,
          listName: ["productName", "productNo"]
        });
      })

      manufacturerInfoApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: "formDataList",
          porp: "manufacturerNo",
          list: res.data,
          listName: ["manufacturerName", "manufacturerNo"]
        });
      })
      proprietorrApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: "formDataOBj",
          formDataListLink: "Manufacturer",
          porp: "proprietorNo",
          list: res.data,
          listName: ["proprietorName", "proprietorNo"]
        });
      })
    },
    async SelectLinkage(e, linkage, index, type, item) {
      console.log("select linkage", e, type, item, linkage);
      if (linkage) {
        let hideData = {}
        for (let i = 0; i < item.typeObj.list.length; i++) {
          let tempData = item.typeObj.list[i]
          if (tempData[type] === e) {
            hideData = tempData
            break
          }
        }
        if (item.porp === 'productNo') {
          for (let i = 0; i < item.typeObj.list.length; i++) {
            let tempData = item.typeObj.list[i]
            if (tempData[item.porp] === e) {
              hideData = tempData
              break
            }
          }
          this.$set(this.formData, 'urlList', hideData.url);
          this.productUploadPictureList = [{ url: hideData.url }];
        }
        if (type === 'proprietorNo') {
          for (let i = index; i < this.formDataOBj.Manufacturer.length; i++) {
            let item = this.formDataOBj.Manufacturer[i]
            if (item.linkChild) {
              // console.log("proprietorNo",item.porpLink,hideData[item.porpLink]);
              this.formData[item.porp][item.porpLink] = hideData[item.porpLink]
              if (item.porpLink === 'proprietor') {
                this.proprietorloadPictureList = hideData['urlList'].map(a => {
                  return { url: a }
                })
                console.log("proprietorloadPictureList", this.proprietorloadPictureList);
              }
            }
          }
          // console.log("Manufacturer data:",this.formDataOBj.Manufacturer);
        } else {
          // console.log("Manufacturer data:", this.formDataList)
          for (let i = index; i < this.formDataList.length; i++) {
            let item = this.formDataList[i]
            if (item.linkChild) {
              this.formData[item.porp] = hideData[item.porp]
            }
          }
          // console.log("formDataList data:",this.formDataList);
        }
      }
    },
    sortRow(item, index) {
      this.$set(this.formData[`${item.porp}`][index], 'unitSymbol', item.unitName);
      this.$set(this.formData[`${item.porp}`][index], 'dataItemName', item.name);
    },
    // 栋舍获取对应栏舍
    async tableUpdatePlus(data) {
      console.log("tableUpdatePlus", data);
    },
    cancelPlus() {
      this.formData = {
        manufacturerInfo: {},
        environmentalDataList: [{}, {}, {}, {}, {}],
        testReportInfoList: [{}],
        AddEnvironmentalDataList: []
      }
      this.environmentalDataList = []
      this.productUploadPictureList = []
      this.proprietorloadPictureList = []
      this.reportUploadPictureList = []
    },
    resetActionBarPlus() {
      console.log(this.formData)
      this.formData = {
        manufacturerInfo: {},
        environmentalDataList: [{}, {}, {}, {}, {}],
        testReportInfoList: [{}]
      }
    },
    addPlus() {
      this.$set(this.formData, 'birthday', dateToFormattwo(new Date()));
      this.$set(this.formData, 'breedTypeNo', sessionStorage.breedTypeNo);
      this.$set(this.formData, 'farmingTypeNo', sessionStorage.farmingTypeNo);
      this.$set(this.formData, 'organizationNo', sessionStorage.organizationNo);
      this.$set(this.formData, 'manufacturerInfo', {
        traceConfigNo: ''
      });
      this.$set(this.formData, 'environmentalDataList', [{}, {}, {}, {}, {}]);
      this.$set(this.formData, 'AddEnvironmentalDataList', []);
      this.$set(this.formData, 'testReportInfoList', [{}]);
      this.$set(this.formData, 'sourceType', '人工录入');
      this.$set(this.formData, 'traceType', '个体');
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          traceType: '个体',
          sourceType: '人工录入',
          ...this.searchObj
        }
      };
      traceConfigApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content
          // console.log("getTableDataList",this.tableData);
          this.resetActionBar();
        }
      });
    },
    editPlus(row) {
      // TODO 点击行元素后 edit
      this.formData = {}
      traceConfigApi.numberQuery(row.traceConfigNo).then((res) => {
        console.log(res);
        let data = res.data;
        if (res.code === 1) {
          this.TestReportr(data);
          this.environmentalDatas(data);
        } else {
          this.$message.warning(res.msg);
        }
      });
      if (row.product.url) {
        this.productUploadPictureList = [{ url: row.product.url }]
        this.formData.urlList = row.product.url
      }
      this.formData.traceConfigNo = row.traceConfigNo;
      this.formData.individuationInfoNo = row.individuationInfo.individuationInfoNo

      this.$set(this.formData, 'productNo', row.productNo)
      this.$set(this.formData, 'birthday', row.individuationInfo.birthday)
      this.$set(this.formData, 'breedVarietyNo', row.individuationInfo.breedVarietyNo)
      this.$set(this.formData, 'gender', row.individuationInfo.gender)
      this.$set(this.formData, 'manufacturerNo', row.manufacturerNo)
      this.$set(this.formData, 'growdate', [row.individuationInfo.groupDate, row.individuationInfo.outlierDate])
      this.formData.address = row.manufacturer.address
      this.formData.director = row.manufacturer.director

      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
      this.Manufacturer(row);
      console.log("handleEdit", this.formData);
    },
    async TestReportr(row) {
      this.$set(this.formData, 'testReportInfoList', row.testReportInfoList)
      this.reportUploadPictureList = []
      if (row.testReportInfoList) {
        row.testReportInfoList.forEach(report => {
          this.reportUploadPictureList.push({})
          let index = this.reportUploadPictureList.length - 1
          this.reportUploadPictureList[index] = report.urlList?.map(item => {
            return { url: item }
          })
        })
      }
      console.log("TestReportr", this.reportUploadPictureList);
    },
    async environmentalDatas(row) {
      if (row.environmentalDataList) {
        this.$set(this.formData, 'environmentalDataList', row.environmentalDataList.splice(0, 5))
        // console.log("environmentalData 1",row.environmentalDataList);
        if (row.environmentalDataList) {
          this.$set(this.formData, 'AddEnvironmentalDataList', row.environmentalDataList)
          this.environmentalDataList = row.environmentalDataList
        }
      }
    },
    async Manufacturer(row) {
      let manufacturerInfo = {
        address: row.proprietor.address,
        contact: row.proprietor.contact,
        director: row.proprietor.director,
        introduction: row.proprietor.introduction,
        scale: row.proprietor.scale,
        urlList: row.proprietor.urlList,
        proprietorNo: row.proprietor.proprietorNo
      }
      this.$set(this.formData, 'manufacturerInfo', manufacturerInfo)
      this.proprietorloadPictureList = row.proprietor.urlList.map(a => { return { url: a } })
    },
    handleSelectionChange(list) {
      this.selectedList = [];
      this.selectedList = list.map(item => item.traceConfigNo);
      if (this.selectedList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      traceConfigApi.numberBatchDel({ noList: this.selectedList }).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          traceConfigApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除"
          // });
        });
    },
    delCountList(item, type, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          this.formData.testReportInfoList.splice(index, 1)
          this.reportUploadPictureList.splice(index, 1)
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除"
          // });
        });
    },
    save(formData) {
      console.log(this.formData);
      this.$refs[formData].validate(valid => {
        if (valid) {
          let params = {
            farmingTypeNo: this.formData.farmingTypeNo,
            factoryDate: dateToFormattwo(new Date()),
            breedVarietyNo: this.formData.breedVarietyNo,
            manufacturerNo: this.formData.manufacturerNo,
            productNo: this.formData.productNo,
            proprietorNo: this.formData.manufacturerInfo.proprietorNo,
            sourceType: '人工录入',
            traceType: '个体',
            individuationInfo: {
              birthday: this.formData.birthday,
              groupDate: this.formData.growdate[0],
              outlierDate: this.formData.growdate[1],
              breedTypeNo: this.formData.breedTypeNo,
              breedVarietyNo: this.formData.breedVarietyNo,
              farmingTypeNo: this.formData.farmingTypeNo,
              organizationNo: sessionStorage.organizationNo,
              gender: this.formData.gender
            },
            testReportInfoList: this.formData.testReportInfoList,
            environmentalDataList: this.formData.environmentalDataList
          }
          params.testReportInfoList = this.formData.testReportInfoList;
          params.environmentalDataList = this.formData.environmentalDataList;
          this.environmentalDataList.forEach(item => {
            item.dataTypeName = item.dataItemName
            params.environmentalDataList.push(item)
          })
          if (this.nowChanceStau === "edit") {
            params.traceConfigNo = this.formData.traceConfigNo
            params.individuationInfo.individuationInfoNo = this.formData.individuationInfoNo
            // 编辑接口
            traceConfigApi.edit(params).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            traceConfigApi.add(params).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
// .staff-manage {
//   width: 100%;
//   height: 100%;
.formStuats {
  // position: absolute;
  // bottom: 80px;
  // right: 10px;
  display: inline-block;
  // width: 60px;
  // height: 32px;
  // line-height: 30px;
  // font-size: 16px;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
  // border-radius: 5px;
  box-shadow: 0 0 5px 0 #00000040;
  background-color: #1F74C7;
  color: #fff;
  margin-right: 10px;
  &:hover {
    background-color: #006f9128;
    border-color: #1F74C7;
    color: #06d4f8;
  }
}
::v-deep .el-form-item__content {
  // display: flex;
  justify-content: space-between;
}
::v-deep .el-form-item__label {
  min-width: 120px !important;
  text-align: end;
}
// }
// }
.DownExcel {
  margin-left: 20px;
  // background-color: #03bfef;
  // // border: 1px solid ;
}
::v-deep {
  .el-input-number {
    width: 100%;
  }
  .el-input-group__append {
    min-width: 80px;
    overflow: hidden;
    text-align: center;
    padding: 0;
  }
  .el-divider__text {
    background-color: #f0f3f7;
  }
}
::v-deep .el-form-item__content{
  align-items: flex-start !important;
}
::v-deep .pull-right {
  // height: 28px;
  // margin-left: 10px;
  .upload-demo {
    height: 100%;
    .el-upload {
      height: 100%;
      .el-button {
        height: 100%;
      }
    }
  }
}

::v-deep {
  .el-form {
    .el-form-item.environmental {
      .el-form-item__content {
        flex-wrap: nowrap !important;
        .line-click {
          right: -40px;
          margin-bottom: 0;
        }
      }
    }
  }
}
.addE {
  display: flex;
  justify-content: flex-end;
  padding-right: 30px;
}
.line-click {
  width: 30px;
  height: 30px;
  background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  border: rgb(214, 214, 214) 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  position: absolute;
  right: 0;
  bottom: 0;
  cursor: pointer;
  .el-icon-plus {
    color: white;
  }
  &:nth-last-child(2) {
  bottom: 34px;
  }
}
.line-clicks {
  width: 30px;
  height: 30px;
  // background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  // border: rgb(214, 214, 214) 1px solid;
  color: red;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  text-decoration: underline;
  text-underline-position: under;
  position: relative;
  right: 0;
  bottom: 0;
  cursor: pointer;
}
</style>
